/*globals YUI database */
/*jslint white: true, browser: true, onevar: false, undef: true, nomen: false, eqeqeq: true, plusplus: true, bitwise: true, regexp: false, newcap: true, immed: true, strict: false */
YUI({
    filter: 'raw',
    modules: {
        'v3-dialog': {
            'fullpath': './js/classes/dialog/dialog.js',
            'type': 'js',
            'requires': ['overlay', 'dd-plugin']
        },
        'v3-dialog-stack': {
            'fullpath': './js/classes/dialog/dialog-stack.js',
            'type': 'js',
            'requires': ['v3-dialog']
        },
        'v3-datatable-filter-datasource': {
            'fullpath': './js/classes/datatable/datatable-filter-datasource.js',
            'type': 'js',
            'requires': ['datatable-base', 'recordset-filter', 'plugin', 'datasource-local']
        }
    }
}).use('datatable-sort', 'datatable-scroll', 'substitute', 'stylesheet', 'v3-dialog-stack', 'v3-datatable-filter-datasource', function (Y) {
    var YL = Y.Lang;
    var formatCompositeButton = function (cellData) {
            // celldata = {tbody, tr, td, classnames, headers, rowindex, record, column, data, value}
            var property;
            var data = cellData.data;
            for (property in data) {
                if (data.hasOwnProperty(property) && Y.Lang.isArray(data[property])) {
                    return Y.substitute('<button id="button-{key}" type="button">Expand</button>', data);
                }
            }
            return '';
        };

    var data = database.entryList.sort(function (rec1, rec2) {
            var key1 = rec1.key,
                key2 = rec2.key;

            if (key1 < key2) {
                return -1;
            } else if (key2 < key1) {
                return 1;
            }
            return 0;
        });

    var getRecord = function (data, x) {
        var low = 0,
            high = data.length - 1,
            mid,
            y;

        while (low <= high) {
            mid = Math.floor((low + high) / 2);
            y = data[mid].key;
            if (y < x) {
                low = mid + 1;
            } else if (y > x) {
                high = mid - 1;
            } else {
                return data[mid];
            }
        }
        return null;
    };

    var columnConfig = [
            {
                "key": "key",
                "label": "Clave",
                "sortable": true,
                "width": "60px"
            },
            {
                "key": "key",
                "label": "Compuesto",
                "formatter": formatCompositeButton,
                "width": "70px"
            },
            {
                "key": "description",
                "label": "Descripcion",
                "sortable": true,
                "width": "400px"
            },
            {
                "key": "unit",
                "label": "Unidad",
                "sortable": true,
                "width": "80px"
            },
            {
                "key": "price",
                "label": "Precio U.",
                "sortable": true,
                "width": "80px"
            }
        ];

    var container = Y.one('.database');

    var dt1 = new Y.DataTable.Base({
            "columnset": columnConfig,
            "recordset": data,
            "summary": "All prices in the database",
            "caption": "Unit price database"
        });

    var dialogStack = new Y.V3_Dialog_Stack();

    dt1.plug(Y.Plugin.DataTableScroll, {
        'height': '400px',
        'COLOR_COLUMNFILLER': 'FF0000'
    });
    dt1.plug(Y.Plugin.DataTableSort);
    dt1.plug(Y.Plugin.V3_DataTableFilterDataSource);
    dt1.render(container);

    var filterBy = Y.one('#filterBy');

    filterBy.on('change', function (event) {
        var target = event.target,
            value = target.get('value');

        if (value === 'All') {
            dt1.filterdatasource.load();
        } else {
            dt1.filterdatasource.load({
                'key': 'category',
                'value': value
            });
        }
    });

    Y.delegate('click', function (event) {
        var target = event.target,
            id = target.get('id'),
            key = id.substr(7),
            record = getRecord(data, key),
            dialog = dialogStack.findInStack(id);

        if (dialog) {
            dialogStack.bringToTop(dialog);
        } else {
            var expandedData = [];
            var property;

            for (property in record) {
                if (record.hasOwnProperty(property) && YL.isArray(record[property])) {
                    expandedData = expandedData.concat(record[property]);
                }
            }

            var dt = new Y.DataTable.Base({
                    'columnset': columnConfig,
                    'recordset': expandedData,
                    'id': 'datatable-' + key,
                    'width': '100%'
                }).plug(Y.Plugin.DataTableSort).render();

            dialog = dialogStack.newDialog({
                id: key,
                width: "600px",
                close: true,
                draggable: true,
                bodyContent: Y.one('#datatable-' + key),
                title: key
            });
            dialog.render();

            dialog.on('destroy', function (event) {
                dt.destroy();
            });
        }
    }, container, "button");
});
